package leecode.q1679;

import java.util.*;

class Solution {
    Map<String, Data> map = new HashMap<>();

    List<String> res = new ArrayList<>();
    List<String> res1 = new ArrayList<>();

    public List<String> invalidTransactions(String[] transactions) {
        Arrays.sort(transactions, new Comparator<String>() {
            @Override
            public int compare(String o1, String o2) {
                String[] split1 = o1.split(",");
                String[] split2 = o2.split(",");
                if (split1[0].compareTo(split2[0]) > 0) {
                    return 1;
                } else if (split1[0].compareTo(split2[0]) < 0) {
                    return -1;
                } else
                    return Integer.parseInt(split1[1]) - Integer.parseInt(split2[1]);
            }
        });
        for (int i = 0; i < transactions.length; i++) {
            String transaction = transactions[i] + "," + i;
            String[] split = transaction.split(",");
            String name = split[0];
            Data value = new Data(split);
            if (isToMuch(value)) {
                if (istoShort(name, value)) {
                    addStringRes(name, map.get(name));
                }
                addStringRes(name, value);
            } else if (istoShort(name, value)) {
                addStringRes(name, map.get(name));
                addStringRes(name, value);
            }
            map.put(name, value);
        }
        for (String re : res) {
            String substring = re.substring(0, re.length() - 1);
            res1.add(substring);
        }
        return res1.isEmpty() ? new ArrayList<>() : res1;
    }

    private void addStringRes(String name, Data value) {
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append(name).append(",");
        stringBuilder.append(value.time).append(",");
        stringBuilder.append(value.count).append(",");
        stringBuilder.append(value.postion).append(value.index);
        if (res.contains(stringBuilder.toString())) {
            return;
        }
        res.add(stringBuilder.subSequence(0, stringBuilder.length()).toString());
    }

    private boolean istoShort(String name, Data value) {
        Data data = map.get(name);
        if (data != null) {
            return Math.abs(value.time - data.time) <= 60;
        }
        return false;
    }

    private boolean isToMuch(Data value) {
        return value.count > 1000;
    }

    class Data {
        int time;

        int count;

        String postion;

        String index;

        public Data(String[] split) {
            this.time = Integer.parseInt(split[1]);
            this.count = Integer.parseInt(split[2]);
            this.postion = split[3];
            this.index = split[4];
        }
    }
}
